import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:camera_platform_interface/camera_platform_interface.dart';
import 'package:rfid/util/toast_util.dart';

import '../event/face_event.dart';
import '../event/qr_event.dart';
import '../http/api.dart';
import '../main.dart';
import '../socket/three_to_one_manager.dart';
import '../util/camera_util.dart';
import '../util/timer_manager.dart';
import 'dart:ui' as ui;

import 'clipper_dialog.dart';

class AuthDialog{

  RxInt select = RxInt(0);
  RxString imgName = RxString('');
  List<String> imgList = ['reader','id','face','oc'];
  ThreeToOneManager manager = ThreeToOneManager();
  CameraUtil camera = CameraUtil();
  Timer? _timer;

  // IdHelper idHelper = IdHelper();


  _auth(String type) async {
    timer.startCountDown(CountDownMode.fast,(){
      _timer?.cancel();
      _timer = null;
      manager.setModeAndStart(Mode.none);
      Get.until((route) => route.isFirst);
    });
    _timer?.cancel();
    _timer = null;
    if(type == '1'){
      tts.speak('请刷读者卡');
      manager.setModeAndStart(Mode.reader);
    }else if(type == '2'){
      tts.speak('请刷身份证');
      manager.setModeAndStart(Mode.identify);
    }else if(type == '3'){
      tts.speak('请刷人脸');
      if(settingEntity.face == 'kd'){
        kdToken();
      }
      manager.setModeAndStart(Mode.none);
      if(camera.cameraId.value == -1){
        camera.cameraId.value = await camera.openCamera();
      }
      if(camera.cameraId.value != -1){
        _start();
      }
    }else if(type == '4'){
      tts.speak('请刷二维码');
      manager.setModeAndStart(Mode.none);
    }
  }

  authTypeDialog({callback}){
    var list = settingEntity.auth!.split('');
    if(list.isEmpty){
      toastWarn('请先配置认证方式');
      return;
    }
    select.value = 0;
    imgName.value = imgList[int.parse(list[0])-1];
    _auth(list[0]);

    Get.defaultDialog(
      title: "",
      barrierDismissible: false,
      contentPadding:EdgeInsets.zero,
      titlePadding:EdgeInsets.zero,
      backgroundColor: Colors.transparent,
      content: Container(
        width: 265.w,
        height: 400.h,
        decoration: const BoxDecoration(
            image: DecorationImage(
              fit: BoxFit.fill,
              image: AssetImage(
                "assets/images/auth_bg.png",
              ),
            )
        ),
        child: Stack(
          alignment: Alignment.topCenter,
          children: [
            Positioned(
                top: 5.h,
                child: Container(
                  height: 30.h,
                  alignment: Alignment.center,
                  child: Text('认证方式',style: TextStyle(color: Colors.white,fontWeight: FontWeight.bold,fontSize: 18.sp,)),
                )
            ),
            Positioned(
                top: 5.h,
                right: 28.w,
                child: Container(
                  height: 30.h,
                  alignment: Alignment.center,
                  child: Obx(() => Text('${timer.fastTime.value}s',style: TextStyle(color: Colors.white,fontSize: 10.sp),textAlign: TextAlign.center,)),
                )
            ),

            Positioned(
                top: 5.h,
                right: 10.w,
                child: InkWell(
                  onTap: (){
                    manager.setModeAndStart(Mode.none);
                    timer.cancel();
                    _timer?.cancel();
                    _timer = null;
                    if(callback != null){
                      callback();
                    }
                    Get.back();

                  },
                  child: Container(
                      height: 30.h,
                      alignment: Alignment.center,
                      child: Icon(Icons.close,color: Colors.white,size: 20.sp,)
                  ),
                )
            ),
            Positioned(
                top: 50.h,
                left: 0,
                right: 0,
                child: Obx(() =>
                  imgName.value=="face"?
                  Column(
                    children: [
                      Text('请把人脸放在扫描区内',style: TextStyle(fontSize: 12.sp, color: Colors.white, fontWeight: FontWeight.bold)),
                      if(camera.cameraId.value > 0)...[
                        RepaintBoundary(
                          key: _globalKey,
                          child:  ClipOval(
                            clipper: ClipperDialogOvalPath(),
                            child:  Transform.scale(
                              scale:settingEntity.scale1??2,
                              child: Transform.translate(offset: Offset((settingEntity.translateX1??0).w,(settingEntity.translateY1??0).h),
                                child: RotatedBox(
                                  quarterTurns: 0,
                                  child: AspectRatio(
                                      aspectRatio: camera.getPreviewSize(),
                                      child: CameraPlatform.instance.buildPreview(camera.cameraId.value)
                                  ),
                                ),),
                            ),
                          ),
                        )
                      ],
                      // Positioned(top:200.h,left:0,right:0
                      //   ,child: Align(child: Text('请把人脸放在扫描区内',style: TextStyle(fontSize: 12.sp, color: Colors.white, fontWeight: FontWeight.bold)),),)
                    ],
                  ):
                  Align(
                    child: Column(
                      children: [
                        SizedBox(height: 50.h,),
                        Image.asset("assets/images/${imgName.value}_big.png", width: 90.w, fit: BoxFit.fitWidth,),
                        SizedBox(height: 10.h,),
                        imgName.value=="reader"?
                        Text('读者卡',style: TextStyle(fontSize: 12.sp, color: Colors.black, fontWeight: FontWeight.bold)):
                        imgName.value=="id"?
                        Text('身份证',style: TextStyle(fontSize: 12.sp, color: Colors.black, fontWeight: FontWeight.bold)):
                        imgName.value=="oc"?
                        _qr():
                        Text('',style: TextStyle(fontSize: 12.sp, color: Colors.black, fontWeight: FontWeight.bold)),
                      ],
                  )),
                )
            ),
            Positioned(
                top: 285.h,
                left: 0,
                right: 0,
                child: Container(
                  alignment: Alignment.center,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Obx(() => _authItem(0,list),),
                      if (list.length > 1) ...<Widget>[
                        Obx(() => _authItem(1,list),),
                      ],
                      if (list.length > 2) ...<Widget>[
                        Obx(() => _authItem(2,list),),
                      ],
                      if (list.length > 3 )...<Widget>[
                        Obx(() => _authItem(3,list),),
                      ],
                    ],
                  ),
                )
            ),
          ],
        ),
      ),
    );
  }

  _qr(){
    return Column(
      crossAxisAlignment: CrossAxisAlignment.center,
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        SizedBox(
          width: 90.w,
          height: 30.h,
          child: TextField(
            minLines: 1,
            textInputAction: TextInputAction.done,
            decoration: InputDecoration(
                isCollapsed: true,
                hintText: "请扫描电子借阅证",
                // border: InputBorder.none,
                hintStyle: TextStyle(color: Colors.blue,fontSize: 8.sp)
            ),
            onChanged: (value){
              _send(value);
            },
            style: TextStyle(color: Colors.blue,fontSize: 8.sp),
            autofocus: true,
          ),

        )
      ],
    );
  }

  Timer? _sendTimer;
  _send(value){
    _sendTimer?.cancel();
    _sendTimer = null;
    _sendTimer = Timer.periodic(const Duration(milliseconds: 500), (timer) {
      eventFactory.fire(QrEvent(value));
      _sendTimer?.cancel();
      _sendTimer = null;
    });

  }


  _authItem(index,list){
    var pos = int.parse(list[index]);
    return InkWell(
      onTap: (){
        if(select.value != index){
          select.value = index;
          imgName.value = imgList[pos-1];
          _auth('$pos');
        }
      },
      child: Container(
        width: 50.w,
        height: 62.h,
        padding: EdgeInsets.only(left: 8.w,right: 8.w,top: 8.h,bottom: 8.h),
        margin: EdgeInsets.only(left: 5.w,right: 5.w),
        decoration: select.value == index?const BoxDecoration(
          image: DecorationImage(
            fit: BoxFit.fill,
            image: AssetImage(
              "assets/images/auth_type_bg.png",
            ),
          ),
        ):const BoxDecoration(),
        child: Image.asset("assets/images/${imgList[pos-1]}_small.png",fit: BoxFit.fitHeight,),
      ),
    );
  }
  final GlobalKey _globalKey = GlobalKey();

  _start(){
    _timer = Timer.periodic(const Duration(seconds: 5), (timer) {
      // _widgetToImage();
      _computeTakePicture();
    });
  }

  _widgetToImage() {
    RenderRepaintBoundary render = _globalKey.currentContext!.findRenderObject() as RenderRepaintBoundary;
    render.toImage().then((image){
      image.toByteData(format: ui.ImageByteFormat.png).then((byteData){
        if(byteData != null){
          String base64 = base64Encode(byteData.buffer.asUint8List());
          String base64Image = "data:image/png;base64,$base64";
          faceSearch(base64Image).then((data){
            if(data.$1 != null){
              if(currentTask.uid == null){
                eventFactory.fire(FaceEvent(data.$1.userId));
                timer.cancel();
                _timer?.cancel();
                _timer = null;
              }
            }else{
              toastWarn('${data.$2}');
            }
          });
        }
      });
    });
  }

  _computeTakePicture() async {
      XFile file = await CameraPlatform.instance.takePicture(camera.cameraId.value);
      // var data = await compute(_takePicture, file);
      var bytes = await file.readAsBytes();
      String base64 = base64Encode(bytes);
      String base64Image = "data:image/png;base64,$base64";
      _searchFace(base64Image);
      File f = File.fromUri(Uri.file(file.path));
      f.delete();
  }

  _searchFace(base64Image) async {
    if(settingEntity.face == 'kd'){
      kdFaceSearch(base64Image).then((data){
        if(data.$1 != null){
          if(currentTask.uid == null){
            // currentTask.uid = data.$1.userId;
            eventFactory.fire(FaceEvent(data.$1));
            timer.cancel();
            _timer?.cancel();
            _timer = null;
          }
        }else{
          toastWarn('${data.$2}');
        }
      });
    }else{
      var data = await faceSearch(base64Image);
      if(data.$1 != null){
        if(currentTask.uid == null){
          // currentTask.uid = data.$1.userId;
          eventFactory.fire(FaceEvent(data.$1.userId));
          timer.cancel();
          _timer?.cancel();
          _timer = null;
        }
      }else{
        toastWarn('${data.$2}');
      }
    }

  }

}